package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func getHeaders() map[string]string {

	hmap := map[string]string{

		"content-type": "application/json",
		"Accept":       "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
		"User-Agent":   "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.35",

		"Accept-Language": "zh-CN,zh;q=0.9",
	}

	return hmap
}

func HttpGet(host, api string) (*MessageData, error) {

	msgdata := MessageData{}

	client := http.Client{}

	params := url.Values{}
	strurl := fmt.Sprintf("%s/%s", host, api)
	parseURL, err := url.Parse(strurl)
	if err != nil {
		fmt.Printf("convert url err: %s\n", err.Error())
		return nil, err
	}

	//如果参数中有中文参数,这个方法会进行URLEncode
	parseURL.RawQuery = params.Encode()
	urlPathWithParams := parseURL.String()

	req, err := http.NewRequest(http.MethodGet, urlPathWithParams, nil)
	if err != nil {
		fmt.Printf("create request err:%s\n", err.Error())
		return nil, err
	}
	// 添加请求头
	for k, v := range getHeaders() {
		req.Header.Add(k, v)
	}
	resp, err := client.Do(req)
	if err == nil {
		b, err := ioutil.ReadAll(resp.Body)
		if err == nil {
			//mt.Println(string(b))
			err = json.Unmarshal(b, &msgdata)
			if err == nil {

				return &msgdata, nil
			} else {

				return nil, err
			}
		}
	}

	return nil, err
}
